package com.qf.servlet;

import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Hou
 * @version V1.0
 * @Project day42
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/12 9:43
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取前端传入的参数。
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");

//        从session 中获取保存的验证码
        HttpSession session = request.getSession();
        String validateCode = (String)session.getAttribute("validateCode");

        //先判断验证码
        if(MyUtil.isEmpty(validateCode)){
//            重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //判断验证码是否正确
        if(!code.equals(validateCode)){
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //判断用户名密码是否为空
        if(MyUtil.isEmpty(uname) || MyUtil.isEmpty(pwd)){
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //走登录的逻辑 调用业务层的内容
        UserService service = new UserServiceImpl();
        boolean result = service.login(uname,pwd);

        if(result){
            session.setAttribute("uname", uname);
            //登录成功
            response.sendRedirect(request.getContextPath()+"/bookList");
        }else{
            //登录失败，重新登录
            response.sendRedirect(request.getContextPath()+"/login.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
